package cn.hnh.shiro;

import cn.hnh.mapper.UserMapper;
import cn.hnh.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author HuangNianHong
 * @Time 2021/1/27
 * 登录操作的Realm
 */
@Component
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

   public LoginRealm(HashedCredentialsMatcher hashedCredentialsMatcher){
       this.setCredentialsMatcher(hashedCredentialsMatcher);   //密码加密散列
   }

    /**
     *  这里由于实现了两个Realm 在进行登录/验证时由此确定是哪个具体的Realm
     *  由于在登录时传的参数是UsernamePasswordToken 因此登录操作的认证授权在此Realm做
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = userMapper.getUserByUserName(username);
        if(user==null)
            return null;
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),"LoginRealm");
    }
}
